﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Threading;
using System.Threading;
using System.Net;
using Flitter.Properties;
using System.ServiceModel.Dispatcher;
using System.IO;

namespace Flitter.Twitter
{
    public class TwitterDataModel : DataModel
    {

        private JsonQueryStringConverter converter = new JsonQueryStringConverter();

        private Statuses _statuses;
        private users _users;
        private DispatcherTimer _timer;

        public TwitterDataModel()
        {
            _twitters = new ObservableCollection<usersUser>();
            _statusList = new ObservableCollection<StatusWrapper>();
        }
        private ObservableCollection<usersUser> _twitters;

        public ObservableCollection<usersUser> Twitters
        {
            get { return _twitters; }
        }
        private ObservableCollection<StatusWrapper> _statusList;

        public ObservableCollection<StatusWrapper> StatusList
        {
            get { return _statusList; }
        }

        public void DoFetch()
        {
            VerifyCalledOnUIThread();
            this.State = ModelState.Fetching;
            if (!ThreadPool.QueueUserWorkItem(new WaitCallback(FetchTwitters)))
            {
                this.State = ModelState.Invalid;
            }
            if (!ThreadPool.QueueUserWorkItem(new WaitCallback(FetchStatusList)))
            {
                this.State = ModelState.Invalid;
            }


        }
        private void FetchTwitters(object state)
        {
            usersUser[] items;

            if (TryGetTwitters(out items))
            {
                this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
                    new ThreadStart(delegate
                    {
                        if (items == null || items.Length == 0)
                        {
                            return;
                        }

                        this._twitters.Clear();
                        foreach (usersUser s in items)
                        {
                            if (s.status != null)
                                this._twitters.Add(s);
                        }
                        this.State = ModelState.Active;
                    }));

            }

            else
            {

                this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,

                    new ThreadStart(delegate
                    { this.State = ModelState.Invalid; }));

            }


        }
        private void FetchStatusList(object state)
        {
            StatusesStatus[] items;

            if (TryGetStatusList(out items))
            {
                this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
                    new ThreadStart(delegate
                    {
                        if(items == null || items.Length == 0)
                        {
                            return;
                        }

                        this._statusList.Clear();
                        foreach (StatusesStatus s in items)
                        {
                            this._statusList.Add(new StatusWrapper(s));
                        }
                        this.State = ModelState.Active;
                    }));

            }

            else
            {

                this.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,

                    new ThreadStart(delegate
                    { this.State = ModelState.Invalid; }));

            }


        }

        private bool TryGetTwitters(out usersUser[] items)
        {

            try
            {
                this._users = TwitterFrontend.GetUsers();
                items = this._users.Items;
                return true;
            }
            catch (Exception)
            {
                items = null;
                return false;
            }
        }

        private bool TryGetStatusList(out StatusesStatus[] items)
        {

            try
            {
                this._statuses = TwitterFrontend.GetStatuses();
                items = this._statuses.Items;
                return true;
            }
            catch (Exception)
            {
                items = null;
                return false;
            }
        }

        protected override void OnActivated()
        {
            VerifyCalledOnUIThread();

            base.OnActivated();

            _timer = new DispatcherTimer(DispatcherPriority.Background);
            _timer.Interval = TimeSpan.FromSeconds(30);
            _timer.Tick += delegate { DoFetch(); };
            _timer.Start();

            DoFetch();
        }

        protected override void OnDeactivated()
        {
            VerifyCalledOnUIThread();

            base.OnDeactivated();

            _timer.Stop();
            _timer = null;
        }



    }

}
